package com.ikingtech.datav.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.ikingtech.datav.api.ProxyRequestApi;
import com.ikingtech.datav.model.request.ProxyRequestDTO;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Enumeration;

/**
 * created on 2024-03-20 15:33
 *
 * @author wub
 */

@RequiredArgsConstructor
@ApiController(value = "/proxy", name = "可视化大屏-请求代理", description = "服务器代理请求")
public class ProxyRequestController implements ProxyRequestApi {

    @Override
    public Object proxyRequest(@RequestBody @Validated ProxyRequestDTO proxyRequestDTO, HttpServletRequest request) {
        try {
            // 创建HttpRequest对象
            HttpRequest httpRequest = HttpRequest.post(proxyRequestDTO.getProxyApi());
            // 复制原请求的所有header
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = request.getHeader(headerName);
                httpRequest.header(headerName, headerValue);
            }
            // 设置请求方法
            httpRequest.method(Method.valueOf(proxyRequestDTO.getProxyMethod().name()));
            // 发送请求并获取响应
            HttpResponse httpResponse = httpRequest.execute();
            // 根据响应状态码构建ResponseEntity
            HttpStatus status = HttpStatus.resolve(httpResponse.getStatus());
            if (status != null) {
                return ResponseEntity.status(HttpStatus.OK).body(httpResponse.body());
            } else {
                // 如果无法解析状态码，则返回一个错误状态
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("无法代理请求");
            }
        } catch (Exception e) {
            // 异常处理，例如记录日志或返回错误信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal server error: " + HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
